# -*- coding: utf-8 -*-

import cherrypy as _cp
from Cheetah.Template import Template 
import pymongo
from pymongo import Connection   
from pymongo.objectid import ObjectId as _id
import pymongo.json_util
import json 
import zmq 
import time
class SkeletonView:  
    def __init__(self,mongodb,remote_addr='tcp://127.0.0.1:3030'): 
        self.ctx = zmq.Context()
        self.remote_addr = remote_addr 
        self.db = mongodb  
        
    def remote(self,cmd,params,service='t'): 
        req = {
            'cmd': cmd,
            'params': params,
        } 
        sock = self.ctx.socket(zmq.REQ)
        sock.connect(self.remote_addr)  
        sock.send_multipart([service,json.dumps(req)])
        res = json.loads(sock.recv())
        if res['code'] != 200: raise Exception('%s'%res['content'])
        return json.loads(res['content'])
    
    @_cp.expose
    def test(self): 
        return str(Template(file='www/test.html',searchList=[{ 
        }])) 
    
    @_cp.expose
    def skeleton(self,body):
        return str(Template(file='www/blocks/skeleton.html',searchList=[{ 
            'uid': _cp.session['uid'],
            'uname': _cp.session['uname'], 
            'body': body
        }])) 
        
    @_cp.expose
    def fav_stock(self): 
        return str(Template(file='www/blocks/fav_stock.html',searchList=[{  
        }]))  
    @_cp.expose
    def user_follows(self,count=6):
        uid = _cp.session['uid'] 
        user = self.db.users.find_one({'uid':uid},{'follows':[0,100]})
        follow_ids,follow_users = [],[]
        if user and user.has_key('follows'): follow_ids = user['follows']  
        if follow_ids:
            for u in self.db.users.find({'uid':{'$in':follow_ids}}):
                follow_users.append(u)
        follow_users = follow_users[0:count];
        return str(Template(file='www/blocks/follows.html',searchList=[{ 
            'users': follow_users,
            'uid':uid,
        }]))
    @_cp.expose
    def user_profile(self,uid): 
        user = self.db.users.find_one({'uid':uid},
            {'fans_count':1,'tweets_count':1,'follows_count':1,'uid':1,'name':1})
        return str(Template(file='www/blocks/t_user.html',searchList=[{ 
            'user':user, 
        }]))    